package com.block.datapush.service.apipush;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IMemberCommonService;
import com.block.common.service.LogFactory;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.YinYuanApiUtil;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;

/**
 * 银源API
 */
@Service
public class YinYuanApiApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMemberCommonService memberCommonService;

    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = pushApiKeyParam.getCheckUrl();
        String phone = memberSourceInfo.getMobileMd5();


        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("tel", phone);
        paramMap.put("appid", pushApiKeyParam.getApiCode());
        paramMap.put("appkey", pushApiKeyParam.getApiKey());


        log.info("【银源API】撞库开始【queryUrl】{}【bizMap】{}", queryUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(queryUrl)
                .form(paramMap)
                .execute().body();
        log.info("【银源API】撞库结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer errNum = resultObject.getInteger("code");
        String errMsg = resultObject.getString("mes");

        pushApiResult.setCode(errNum + "|" + errMsg);
        pushApiResult.setMessage(errMsg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(errNum), "200")) {
            pushApiResult.setPushSuccess(true);
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();

        return pushApiResult;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);

        String requestUrl = pushApiKeyParam.getRegisterUrl();
        String pubKey = pushApiKeyParam.getPubKey();
        String apiKey = pushApiKeyParam.getApiKey();
        String apiCode = pushApiKeyParam.getApiCode();
        long timestamp = System.currentTimeMillis();
        String noncestr = UUID.randomUUID().toString();

        String city = memberSourceInfo.getCity();

        if (StrUtil.endWith(city, "市")) {
            city = memberSourceInfo.getCity().substring(0, memberSourceInfo.getCity().length() - 1);
        }


        TreeMap<String, Object> paramMap = new TreeMap<>();
        paramMap.put("vender_name", pubKey);
        String channelCode = memberSourceInfo.getChannelCode();
        if(StrUtil.equals(channelCode,"2LW530")||StrUtil.equals(channelCode,"SEX3ID")){
            paramMap.put("channel", "zhenxiangfenqi-yh");
        }else {
            paramMap.put("channel", "zhenxiangfenqi");
        }
        paramMap.put("name", memberSourceInfo.getRealname());
        paramMap.put("city", city);
        paramMap.put("sex", memberSourceInfo.getSex() == 1 ? "男" : "女");
        paramMap.put("telphone", memberSourceInfo.getMobile());
        paramMap.put("birthday", LocalDate.now().getYear()-memberSourceInfo.getAge()+"-"+"01-01");
        paramMap.put("vocation", YinYuanApiUtil.getJob(memberSourceInfo.getGongzuo()));
        paramMap.put("salary", YinYuanApiUtil.getShouru(memberSourceInfo.getShouru()));
        paramMap.put("loan_amount", YinYuanApiUtil.getloan(memberSourceInfo.getLoanAmount()));
        paramMap.put("loan_time", YinYuanApiUtil.getLoanTime(memberSourceInfo.getLoanTime()));
        paramMap.put("have_credit_card", YinYuanApiUtil.getXinyongka(memberSourceInfo.getXinyongka()));
        paramMap.put("have_house", YinYuanApiUtil.getHouse(memberSourceInfo.getHouse()));
        paramMap.put("have_car", YinYuanApiUtil.getCar(memberSourceInfo.getCar()));
        paramMap.put("shebao", YinYuanApiUtil.getshebao(memberSourceInfo.getShebao()));
        paramMap.put("have_fund", YinYuanApiUtil.getGjj(memberSourceInfo.getGjj()));
        paramMap.put("have_baoxian", YinYuanApiUtil.getbaodan(memberSourceInfo.getBaoxian()));

        paramMap.put("appid", apiCode);
        paramMap.put("appkey", apiKey);
        paramMap.put("noncestr", noncestr);
        paramMap.put("timestamp", timestamp);
        paramMap.put("signature",sha1Encrypt(joinTreeMap(paramMap)));


        log.info("【银源API】导单开始【requestUrl】{}【paramMap】{}", requestUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(requestUrl)
                .form(paramMap)
                .execute().body();
        log.info("【银源API】导单结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        String resStatus = resultObject.getString("resStatus");
        String resMsg = resultObject.getString("resMsg");


        pushApiResult.setCode(resStatus);
        pushApiResult.setMessage(resMsg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(resStatus), "1")) {
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(true);
            pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
            return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }


    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        return null;
    }

    /**
     * 字段拼接
     *
     * @param treeMap 排序后的请求参数
     * @return 字符串
     * @date 2024/3/1
     */
    private static String joinTreeMap(Map<String, Object> treeMap) {
        if (treeMap == null || treeMap.size() == 0) {
            return StringUtils.EMPTY;
        }
        StringBuilder builder = new StringBuilder();
        for (Map.Entry<String, Object> paramKeyAndValue : treeMap.entrySet()) {
            builder.append(paramKeyAndValue.getKey()).append("=");
            builder.append(paramKeyAndValue.getValue()).append("&");
        }
        return builder.substring(0, builder.length() - 1);
    }


    /**
     * SHA1加密
     * */
    public static String sha1Encrypt(String input) {
        try {
            // 获取一个SHA-1加密对象
            MessageDigest md = MessageDigest.getInstance("SHA-1");

            // 对输入字符串进行加密
            byte[] messageDigest = md.digest(input.getBytes());

            // 将字节数组转为十六进制的字符串
            StringBuilder sb = new StringBuilder();
            for (byte b : messageDigest) {
                sb.append(String.format("%02x", b & 0xff));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {

        String channelCode ="2LW530";
        if(StrUtil.equals(channelCode,"2LW530")||StrUtil.equals(channelCode,"SEX3ID")){

            System.out.println("zhenxiangfenqi-yh");
        }else {

            System.out.println("zhenxiangfenqi");
        }
    }

}
